import {
  env
} from './env.js'

const LOG_SUCCESS = '\x1B[32m%s\x1B[0m'
const LOG_FAIL = '\x1B[31m%s\x1B[0m'

const request = (params) => {

  const needLoading = params.hasOwnProperty('needLoading') ? params.needLoading : false

  let loading = true
  if (needLoading && loading) {
    uni.showLoading({
      title: '加载中',
      mask: true
    })
  }

  // 除了登录接口外，都需要token
  const token = params.url !== '/user/mobilelogin' || params.url !== '/column/list' ? uni.getStorageSync('userInfo')
    .token : ''
  return new Promise((resolve, reject) => {
    uni.request({
      url: env.baseUrl + (params.url || ''),
      method: params.method || 'POST',
      timeout: 60000,
      sslVerify: true, // 本地真机调试要改成false
      header: {
        'content-type': (params.header && params.header['content-type']) ||
          'application/json',
        ...params.header,
        token: token
      },
      data: params.data || {},

      success: (res) => {
        if (res.data.code === 401) {
          // #ifdef H5
          if (/micromessenger/.test(navigator.userAgent.toLowerCase())) {
            uni.removeStorageSync('userInfo')
            uni.reLaunch({
              url: '/pages/loginPage/login-wx/index'
            })
          } else {
            uni.removeStorageSync('userInfo')
            uni.showToast({
              title: res.data.msg,
              icon: 'none'
            })
            uni.navigateTo({
              url: '/pages/loginPage/index'
            })
            return
          }
          // #endif
          // #ifndef H5
          uni.removeStorageSync('userInfo')
          uni.showToast({
            title: res.data.msg,
            icon: 'none'
          })
          uni.navigateTo({
            url: '/pages/loginPage/index'
          })
          return
          // #endif
        }
        resolve(res.data)
      },
      fail: (err) => {
        reject(err)
      },
      complete: () => {
        if (needLoading && loading) {
          uni.hideLoading()
        }
        loading = false
      }
    })
  })
}

export default request